package LC;

import java.math.BigInteger;

/**
 * https://leetcode.com/problems/divide-two-integers/description/
 * Divide two integers without using multiplication, division and mod operator.
 * If it is overflow, return MAX_INT.
 */
public class LC_029_DivideTwoIntegers_Math_JavaAPI {
    public static void main(String[] args) {

    }

    static class Solution_1 {
        public int divide(int dividend, int divisor) {
            if (divisor == 0)
                return Integer.MAX_VALUE;
            if (divisor == -1 && dividend == Integer.MIN_VALUE)
                return Integer.MAX_VALUE;
            long pDividend = Math.abs((long) dividend);
            long pDivisor = Math.abs((long) divisor);
            int result = 0;
            while (pDividend >= pDivisor) {
                int numShift = 0;
                while (pDividend >= (pDivisor << numShift))
                    numShift++;
                result += 1 << (numShift - 1);
                pDividend -= (pDivisor << (numShift - 1));
            }
            if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0))
                return result;
            else
                return -result;
        }
    }

    static class Solution_2 {
        public int divide(int dividend, int divisor) {
            if (divisor == 0)
                return Integer.MAX_VALUE;
            if (divisor == -1 && dividend == Integer.MIN_VALUE)
                return Integer.MAX_VALUE;
            return new BigInteger(String.valueOf(dividend)).divide(new BigInteger(String.valueOf(divisor))).intValue();
        }
    }

}
